﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReactiveTest
{
    public sealed class SimpleObservable : IObservable<int>
    {
        IDisposable IObservable<int>.Subscribe(IObserver<int> observer)
        {
            SimpleDisposable disposable = new();

            Task.Run(() =>
            {
                // 模拟数据的生产，以及假设每次生产都需要时间，消费者可以随时调用Dispose方法取消订阅
                for (int i = 1; i <= 5; i++)
                {
                    if (disposable.IsDisposed)
                    {
                        return;
                    }
                    observer.OnNext(i);
                    // 模拟产生数据需要耗时50毫秒
                    Thread.Sleep(50);
                }

                observer.OnCompleted();
            });

            return disposable;
        }

        private sealed class SimpleDisposable : IDisposable
        {
            internal bool IsDisposed { get; private set; }

            void IDisposable.Dispose()
            {
                IsDisposed = true;
                Console.WriteLine("Subscription disposed.");
            }
        }
    }
}